
#include "IResource.h"

using namespace BWE;

IResource::IResource()
{
	_mode = IO_None;
	_bytes = 0;
	_size = 0;
	_offset = 0;
}
IResource::IResource(const BByte* bytes, int size)
{
	_mode = IO_Read;
	_bytes = bytes;
	_size = size;
	_offset = 0;
}
IResource::~IResource()
{

}

void IResource::reset(const BByte* bytes, int size)
{
	_mode = IO_Read;
	_bytes = bytes;
	_size = size;
	_offset = 0;
}
const BByte* IResource::data() const
{
	return _bytes;
}

IOMode IResource::mode() const
{
	return _mode;
}

bool IResource::seek(int offset) const
{
	if (offset < 0 || offset > _size)
		return false;
	if (_offset != offset)
	{
		_offset = offset;
	}
	return true;
}
bool IResource::wseek(int offset)
{
	return false;
}

bool IResource::empty() const
{
	return _size < 1;
}
void IResource::clear()
{
	_mode = IO_None;
	_bytes = 0;
	_size = 0;
	_offset = 0;
}

bool IResource::begin() const
{
	return _offset == 0;
}
bool IResource::end() const
{
	return _offset == _size;
}

int IResource::size() const
{
	return _size;
}
int IResource::offset() const
{
	return _offset;
}

bool IResource::read(void* data, int size) const
{
	int offset = _offset;
	if (_offset + size > _size)
		return false;
	memcpy(data, _bytes + _offset, size);
	_offset += size;
	return true;
}
bool IResource::write(const void* data, int size)
{
	return false;
}

bool IResource::read(BString& text) const
{
	text.reset();
	while (1)
	{
		char c = 0;
		if (!read(c))
			break;
		text.append(c);
		if (c == 0)
			break;
	}
	return text.size();
}
bool IResource::write(const BString& text)
{
	return false;
}

bool IResource::readCStr(char* cstr, int maxSize) const
{
	if (!cstr || maxSize <= 0)
		return false;
	char code = 0;
	for (int i = 0; i < maxSize; i++)
	{
		if (!read(code))
		{
			cstr[0] = 0;
			return false;
		}
		cstr[i] = code;
		if (code == 0)
		{
			return true;
		}
	}
	return false;
}
bool IResource::writeCStr(const char* cstr, int size)
{
	return false;
}

bool IResource::readLine(char* cstr, int size) const
{
	for (int i = 0; i < size; i++)
	{
		char c = 0;
		if (!read(&c, 1))
			return i > 0;
		cstr[i] = c;
		if (c == '\n')
			return i > 0;
	}
	return false;
}
bool IResource::writeLine(const char* cstr, int size)
{
	return false;
}

bool IResource::readLine(BString& line) const
{
	line.reset();
	while (1)
	{
		char c = 0;
		if (!read(&c, 1))
			break;
		line.append(c);
		if (c == '\n')
			break;
	}
	return line.size();
}
bool IResource::writeLine(const BString& line)
{
	return false;
}
